﻿using Core.ApplicationServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Core.DomainServices
{
    public abstract class ICategoryCrawlable
    {
        public readonly IArticleCrawlable crawlable;
        public readonly IConfigurable appConfig;
        public readonly IRepository repository;
        private bool IsLatestItem = false;

        public ICategoryCrawlable(IArticleCrawlable crawlable, IConfigurable appConfig, IRepository repository)
        {
            this.crawlable = crawlable;
            this.appConfig = appConfig;
            this.repository = repository;
        }
        
        public virtual IList<string> Parser(IList<string> categories)
        {
            if (categories == null || categories.Count == 0) return null;
            foreach (var catName in categories)
            {
                Thread.Sleep(1000);
                IsLatestItem = false;

                IList<string> results = new List<string>();
                crawlable.ItemIndex = 1;
                do
                {
                    try
                    {
                        IsLatestItem = crawlable.Parser(catName, results);
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(5000);
                        IsLatestItem = crawlable.Parser(catName, results);
                    }
                } while (!IsLatestItem);

                string workingFolder = appConfig.WorkingFolder + Path.DirectorySeparatorChar + crawlable.GetHost(crawlable.RootUrl);
                repository.AppendItems(workingFolder, catName, results);
            }
            return null;
        }

        public abstract IList<string> GetCategories { get; }
    }
}
